import { defineStore } from 'pinia'
import { userLoginAndReg, userLogoutApi, userGetSize } from '../service/api'
import { ElMessage } from 'element-plus'
import router from '@/router'

export default defineStore('user', {
  state() {
    return {
      user: {},
      token: '',
      total_size: 0,
      used_size: 0,
      dirs: [],
      activeMenu: 0,
      activeIndex: 0
    }
  },
  persist: true,
  actions: {
    async userSize() {
      const { total_size, used_size } = await (await userGetSize()).data.data
      this.total_size = total_size
      this.used_size = used_size
    },
    async userLogout() {
      const res = await userLogoutApi()
      if (res.data.msg === 'ok') {
        ElMessage({
          message: '退出成功!',
          type: 'success'
        })
        this.user = {}
        this.token = ''
        router.push('/login')
      }
    },
    async userActions(payload: { url: string, data: any, message: string }) {
      try {
        const response = await userLoginAndReg(payload.url, payload.data)
        this.user = response.data.data
        this.token = response.data.data.token
        ElMessage({
          message: payload.message,
          type: 'success'
        })
        if (payload.url == '/reg') {
          router.go(0)
        } else {
          router.push('/main')
        }
      } catch (error: any) {
        ElMessage({
          message: error,
          type: 'warning'
        })
      }
    },
    async changeDir(item: { id: number, name: string }) {
      (this.dirs as any).push(item)
    },
    async setdirs(arr: any) {
      this.dirs = arr
    }
  }
})